const cloud = require('wx-server-sdk');
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();
const _ = db.command;

exports.main = async (event, context) => {
  const { activityID } = event;

  if (!activityID) {
    return { success: false, error: "缺少 activityID" };
  }

  try {
    // 查询活动分组
    const groupsRes = await db.collection('Activity_Group_Information')
      .where({ ActivityID: activityID })
      .field({ _id: true, GroupName: true })
      .get();
    const groups = groupsRes.data || [];
    if (groups.length === 0) {
      return { success: true, data: { registrants: [] } };
    }

    // 查询报名信息
    const registrationsRes = await db.collection('Group_Registration_Information')
      .where({ GroupID: _.in(groups.map(g => g._id)) })
      .field({ GroupID: true, OpenID: true, RegistrationTime: true })
      .get();
    const registrations = registrationsRes.data || [];
    if (registrations.length === 0) {
      return { success: true, data: { registrants: [] } };
    }

    // 查询用户信息
    const userProfilesRes = await db.collection('User_Profile')
      .where({ OpenID: _.in(registrations.map(r => r.OpenID)) })
      .field({ Name: true, StudentID: true, OpenID: true })
      .get();
    const users = userProfilesRes.data || [];

    // 整合数据
    const registrants = users.map(user => {
      const userRegs = registrations.filter(r => r.OpenID === user.OpenID);
      const userGroups = userRegs.map(r => ({
        groupID: r.GroupID,
        groupName: groups.find(g => g._id === r.GroupID)?.GroupName || '',
        registrationTime: r.RegistrationTime || ''
      }));
      return {
        name: user.Name || '',
        openID: user.OpenID || '',
        studentID: user.StudentID || '',
        groups: userGroups
      };
    });

    // 返回结果
    return {
      success: true,
      data: { registrants }
    };

  } catch (error) {
    return {
      success: false,
      error: error.message || error
    };
  }
};
